package com.sunday.pinxinghui.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.common.widgets.gridview.NoScrollGridView;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.BannerImg;
import com.sunday.pinxinghui.entity.CatProduct;
import com.sunday.pinxinghui.entity.HeadProduct;
import com.sunday.pinxinghui.entity.IndexProduct;
import com.sunday.pinxinghui.event.UpdateCartNum;
import com.sunday.pinxinghui.model.products.ProductDetailActivity;
import com.sunday.pinxinghui.model.products.ProductsListActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.RoundingMode;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by AnyOne on 2018/4/9.
 */

public class TodayAdapter extends RecyclerView.Adapter {


    private Context mContext;
    private List<CatProduct> dataSet;
    private List<IndexProduct> limitProducts;
    private List<BannerImg> bannerImgs;
    private final static int TYPE_BANNER = 0;
    private final static int TYPE_LIST = 1;
    private String qgImg;

    private View.OnClickListener onClickListener;


    public TodayAdapter(Context context, List<IndexProduct> limitProducts, List<CatProduct> catProducts, List<BannerImg> bannerImgs, String qgImg) {
        this.mContext = context;
        this.limitProducts = limitProducts;
        this.dataSet = catProducts;
        this.bannerImgs = bannerImgs;
        this.qgImg = qgImg;
    }


    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_BANNER;
        } else {
            return TYPE_LIST;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        switch (viewType) {
            case TYPE_BANNER:
                view = LayoutInflater.from(mContext).inflate(R.layout.layout_banner, null);
                return new BannerHolder(view);
            case TYPE_LIST:
                view = LayoutInflater.from(mContext).inflate(R.layout.list_today_item, null);
                return new ListHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        switch (getItemViewType(position)) {
            case TYPE_BANNER:
                BannerHolder bannerHolder = (BannerHolder) holder;
                bannerHolder.banner.startTurning(3000);
                final IndexAdHolder indexAdHolder = new IndexAdHolder();
                bannerHolder.banner.setPages(new ViewHolderCreator<IndexAdHolder>() {
                    @Override
                    public IndexAdHolder createHolder() {
                        return indexAdHolder;
                    }
                }, bannerImgs)
                        .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
                bannerHolder.banner.notifyDataSetChanged();
                indexAdHolder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BannerImg item = (BannerImg) v.getTag();
                        if (item.getLinkType() != null && item.getLinkType() == 1) {
                            Intent intent = new Intent(mContext, ProductDetailActivity.class);
                            intent.putExtra("productId", item.getProductId());
                            mContext.startActivity(intent);
                        } else if (item.getCatId() != 0) {
                            //intent = new Intent(mContext, ProductListActivity.class);
                            Intent intent = new Intent(mContext, ProductsListActivity.class);
                            intent.putExtra("parentId", item.getParentCatId());
                            intent.putExtra("catId", item.getCatId());
                            intent.putExtra("parentName", item.getName());
                            mContext.startActivity(intent);
                        }
                    }
                });
                break;
            case TYPE_LIST:
                ListHolder listHolder = (ListHolder) holder;
                if (!limitProducts.isEmpty()) {
                    if (position == 1) {
                        listHolder.tvTitle.setText("限时抢购");
                        listHolder.gridView.setAdapter(new CommenAdapter<IndexProduct>(mContext, limitProducts, R.layout.list_today_product) {

                            @Override
                            public void convert(ViewHolder helper, IndexProduct item, int position) {
                                bindData(helper, item, position);
                            }
                        });
                        Glide.with(mContext).load(ApiClient.IMG_URL + qgImg).into(listHolder.ivCat);
                    } else {
                        CatProduct catProduct = dataSet.get(position - 2);
                        listHolder.tvTitle.setText(catProduct.getName());
                        listHolder.gridView.setAdapter(new CommenAdapter<HeadProduct>(mContext, catProduct.getProducts(), R.layout.list_today_product) {
                            @Override
                            public void convert(ViewHolder helper, HeadProduct item, int position) {
                                bindData(helper, item, position);
                            }
                        });
                        Glide.with(mContext).load(ApiClient.IMG_URL + catProduct.getLogo()).into(listHolder.ivCat);
                    }
                }
                listHolder.llTitle.setTag(R.id.ll_title_id, position);
                listHolder.llTitle.setOnClickListener(onClickListener);

                break;
        }
    }


    private void bindData(ViewHolder helper, final IndexProduct item, int position) {
        ImageView imgView = helper.getView(R.id.product_img);
        TextView recProPriceNow = helper.getView(R.id.product_price);
        recProPriceNow.setText(String.format("¥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
        Glide.with(mContext)
                .load(item.getImage())
                .error(R.mipmap.ic_default)
                .into(imgView);
        TextView recProTitle = helper.getView(R.id.product_title);
        recProTitle.setText(item.getProductName());
        helper.getView(R.id.product_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ProductDetailActivity.class);
                intent.putExtra("productId", item.getProductId());
                mContext.startActivity(intent);
            }
        });
        helper.getView(R.id.iv_cart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCart(item.getProductId());
            }
        });
    }

    private void bindData(ViewHolder helper, final HeadProduct item, int position) {
        ImageView imgView = helper.getView(R.id.product_img);
        TextView recProPriceNow = helper.getView(R.id.product_price);
        recProPriceNow.setText(String.format("¥%s", item.getSalePriceView()));
        Glide.with(mContext)
                .load(ApiClient.IMG_URL + item.getImage())
                .error(R.mipmap.ic_default)
                .into(imgView);
        TextView recProTitle = helper.getView(R.id.product_title);
        recProTitle.setText(item.getProductName());
        helper.getView(R.id.product_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ProductDetailActivity.class);
                intent.putExtra("productId", item.getId());
                mContext.startActivity(intent);
            }
        });
        helper.getView(R.id.iv_cart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCart(item.getId());
            }
        });
    }

    private void addCart(long productId) {
        Call<ResultDO> call = ApiClient.getApiAdapter().addCart(productId, BaseApplication.getInstance().getMember().getId(), null, 1);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "成功加入购物车");
                    EventBus.getDefault().post(new UpdateCartNum());
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    @Override
    public int getItemCount() {
        return limitProducts.isEmpty() ? dataSet.size() : dataSet.size() + 1;
    }

    public void setOnClickListener(View.OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    class BannerHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.banner)
        ConvenientBanner banner;

        public BannerHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class ListHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.tv_title)
        TextView tvTitle;
        @Bind(R.id.grid_view)
        NoScrollGridView gridView;
        @Bind(R.id.ll_title)
        LinearLayout llTitle;
        @Bind(R.id.iv_cat)
        ImageView ivCat;


        public ListHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            int width = DeviceUtils.getDisplay(mContext).widthPixels;
            int height = width / 3;
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);
            ivCat.setLayoutParams(layoutParams);
        }
    }


}
